package com.hui.server.controller;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hui.server.util.ClientIpAddrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: yeb
 * @BelongsPackage: com.hui.server.controller
 * @Author: HUI
 * @CreateTime: 2022-04-04 23:44
 * @Description: 验证码 Controller 未做IP地址异常
 */


@RestController
@Slf4j
public class KaptchaController {

    //redis 模板对象
    private final StringRedisTemplate stringRedisTemplate;

    //默认验证码过期时间 60 * 60
    private static final long KAPTCHA_EXPIRED_SECONDS = 3600L;

    //验证码
    private final Producer producer;


    @Autowired
    public KaptchaController(StringRedisTemplate stringRedisTemplate, Producer producer) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.producer = producer;
    }

    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha", produces = "image/jpeg") //设置返回类型
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        String ipAddress = ClientIpAddrUtil.getIpAddress(request);
        boolean isAddrNotNull = ClientIpAddrUtil.requireIpAddrNotNull(ipAddress);
        log.info("请求的IP地址：{}",ipAddress);
        log.info("IP地址是否存在：{}",isAddrNotNull);


        //IP地址异常处理
/*        if (!isAddrNotNull){
            //......
        }*/


        //定义response输出类型为image/jpeg
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //---------------------------生成验证码----------------------
        //获取验证码文本内容
        String text = producer.createText();
        log.info("获取的验证码：{}",text);

        /*//将验证码放到session中
        request.getSession().setAttribute("captcha", text);*/

        //将验证码以<key,value>形式缓存到redis
        stringRedisTemplate.opsForValue().set(ipAddress,text,KAPTCHA_EXPIRED_SECONDS, TimeUnit.SECONDS);


        //根据文本内容创建图形验证码
        BufferedImage image = producer.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片,格式为jpg
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("获取验证码出错！");
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
